package com.electron.power.aio.mod.cha;

import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.transport.AioSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import com.alibaba.fastjson.JSONObject;
import com.electron.power.aio.common.exception.BizException;
import com.electron.power.aio.mod.str.FlinkModProcessor;
import com.electron.power.model.mod.ModBodyMap;
import com.electron.power.model.mod.ModStr;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class ModCharProcessor implements MessageProcessor<ModStr> {
	@Autowired
	private WebClient.Builder webClientBuilder;

	@Override
	public void process(AioSession<ModStr> session, ModStr msg) {
		try {
			String hostAddress = session.getRemoteAddress().getAddress().getHostAddress();
			log.debug("客户机主机地址为:{}", hostAddress);
		} catch (Exception e) {
			log.error("客户端网络异常", e);
			throw new BizException("客户端网络异常", e);
		}
		log.info("收到客户端的mod信息为:{}", msg);
		Mono<ModBodyMap> modBody = webClientBuilder.build().post().uri("http://localhost/api/mod/modstr/add")
				.contentType(MediaType.APPLICATION_JSON).body(Mono.just(msg), ModStr.class).retrieve()
				.bodyToMono(ModBodyMap.class);
		modBody.subscribe(modBodyMap -> {
			
			try {
				AioSession<String> flinkClientSession = FlinkModProcessor.sessionMap
						.get(FlinkModProcessor.CLIENT_SESSION_NAME);
				String modString = JSONObject.toJSONString(modBodyMap);
				flinkClientSession.writeBuffer().write(modString.getBytes());
				flinkClientSession.writeBuffer().write('\n');
				flinkClientSession.writeBuffer().flush();
			} catch (Exception e) {
				log.error("客户端写数据异常", e);
				throw new BizException("客户端写数据异常", e);
			}
			
			log.info("数据库返回数据为:{}", modBodyMap);
			try {
				String deviceId = String.valueOf(modBodyMap.getDeviceId());
				int length = deviceId.length();
				session.writeBuffer().writeInt(length);
				session.writeBuffer().write(deviceId.getBytes());
				session.writeBuffer().flush();
			} catch (Exception e) {
				log.error("客户端写数据异常", e);
				throw new BizException("客户端写数据异常", e);
			}
		});

		// TODO 发送消息到rabbitMQ.交给项目处理数据.
		// try {
		// session.write(mod);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
	}

	@Override
	public void stateEvent(AioSession<ModStr> session, StateMachineEnum stateMachineEnum, Throwable throwable) {

	}

}
